package com.lishangshan.oas_system.controller.inform;

import com.lishangshan.oas_system.model.dao.informdao.InformDao;
import com.lishangshan.oas_system.model.dao.informdao.InformRelationDao;
import com.lishangshan.oas_system.model.dao.system.StatusDao;
import com.lishangshan.oas_system.model.dao.system.TypeDao;
import com.lishangshan.oas_system.model.dao.user.DeptDao;
import com.lishangshan.oas_system.model.dao.user.UserDao;
import com.lishangshan.oas_system.model.entity.notice.NoticeUserRelation;
import com.lishangshan.oas_system.model.entity.notice.NoticesList;
import com.lishangshan.oas_system.model.entity.system.SystemStatusList;
import com.lishangshan.oas_system.model.entity.system.SystemTypeList;
import com.lishangshan.oas_system.model.entity.user.User;
import com.lishangshan.oas_system.service.inform.InformRelationService;
import com.lishangshan.oas_system.service.inform.InformService;
import com.lishangshan.oas_system.utils.ParameterUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.*;

@Controller
@RequestMapping("/")
public class InformManageController {
    Logger log = LoggerFactory.getLogger(getClass());
    @Autowired
    private StatusDao statusDao;

    @Autowired
    private TypeDao typeDao;

    @Autowired
    private InformDao informDao;

    @Autowired
    private InformService informService;

    @Autowired
    private UserDao uDao;

    @Autowired
    private DeptDao deptDao;

    @Autowired
    private InformRelationDao informrelationDao;

    @Autowired
    private InformRelationService informrelationservice;

    /**
     * 通知面板数据初始化
     *
     * @param page
     * @param userId
     * @param model
     * @return
     */
    @RequestMapping("infrommanage")
    public String inform(@RequestParam(value = "page", defaultValue = ParameterUtil.PAGE_NUMBER) int page, @SessionAttribute("userId") Long userId, Model model) {
        Page<NoticesList> page2 = informService.pageThis(page, userId);
        List<NoticesList> noticeList = page2.getContent();
        List<Map<String, Object>> list = informService.fengZhuang(noticeList);
        model.addAttribute("list", list);
        model.addAttribute("page", page2);
        //设置变量，需要load的url；
        model.addAttribute("url", "infrommanagepaging");
        return "inform/informmanage";
    }

    /**
     * 分页 搜索 ，类型数控制器
     *
     * @param page
     * @param userId
     * @param model
     * @param baseKey
     * @param type
     * @param status
     * @param time
     * @return
     */
    @RequestMapping("infrommanagepaging")
    public String infromPaging(@RequestParam(value = "page", defaultValue = ParameterUtil.PAGE_NUMBER) int page,
                               @SessionAttribute("userId") Long userId, Model model,
                               @RequestParam(value = "baseKey", required = false) String baseKey,
                               @RequestParam(value = "type", required = false) Object type,
                               @RequestParam(value = "status", required = false) Object status,
                               @RequestParam(value = "time", required = false) Object time
    ) {
        Page<NoticesList> listPage = informService.pageThis(page, userId, baseKey, type, status, time);
        List<NoticesList> noticesLists = listPage.getContent();
        List<Map<String, Object>> list = informService.fengZhuang(noticesLists);
        model.addAttribute("list", list);
        model.addAttribute("page", listPage);
        //设置变量，需要load的url；
        model.addAttribute("url", "infrommanagepaging");
        return "inform/informtable";
    }

    /**
     * 存储 类型 和状态 公共方法
     *
     * @param model
     */
    private void somthinglist(Model model) {
        List<SystemTypeList> typeList = typeDao.findByTypeModel("inform");
        List<SystemStatusList> statusList = statusDao.findByStatusModel("inform");
        model.addAttribute("typeList", typeList);
        model.addAttribute("statusList", statusList);
    }

    /**
     * 转向添加 修改
     *
     * @param req
     * @param session
     * @param model
     * @return
     */
    @RequestMapping("informedit")
    public String infromEdit(HttpServletRequest req, HttpSession session, Model model) {
        session.removeAttribute("noticeId");
        somthinglist(model); //
     /*   if (!StringUtils.isEmpty(req.getAttribute("errormess"))) {
            req.setAttribute("errormess", req.getAttribute("errormess"));
        }
        if (!StringUtils.isEmpty(req.getAttribute("success"))) {
            req.setAttribute("success", "数据保存成功");
        }*/
        // 如果id存在 就是修改
        if (!StringUtils.isEmpty(req.getParameter("id"))) {
            Long noticeId = Long.parseLong(req.getParameter("id"));
            NoticesList noticeList = informDao.findOne(noticeId);
            model.addAttribute("noticeList", noticeList);
            model.addAttribute("typeName", typeDao.findOne(noticeList.getTypeId()).getTypeName());
            model.addAttribute("statusName", statusDao.findOne(noticeList.getStatusId()).getStatusName());
            session.setAttribute("noticeId", noticeId);
        }
        return "inform/informedit";
    }

    /**
     * 新增/修改通知验证
     *
     * @param req
     * @param menu
     * @param br
     * @return
     */
    @RequestMapping("informcheck")
    public String testMess(HttpServletRequest req, @SessionAttribute("userId") Long userId, @Valid NoticesList menu, BindingResult br) {
        HttpSession session = req.getSession();
        Long menuId = null;
        req.setAttribute("menuObj", menu);
        menu.setUserId(userId);
 /*  // 这里返回ResultVO对象，如果校验通过，ResultEnum.SUCCESS.getCode()返回的值为200；否则就是没有通过；
        ResultVO res = BindingResultVOUtil.hasErrors(br);
        // 校验失败
        if (!ResultEnum.SUCCESS.getCode().equals(res.getCode())) {
            List<Object> list = new MapToList<>().mapToList(res.getData());
            req.setAttribute("errormess", list.get(0).toString());
            // 代码调试阶段，下面是错误的相关信息；
            System.out.println("list错误的实体类信息：" + menu);
            System.out.println("list错误详情:" + list);
            System.out.println("list错误第一条:" + list.get(0));
            System.out.println("啊啊啊错误的信息——：" + list.get(0).toString());
            // 下面的info信息是打印出详细的信息
            log.info("getData:{}", res.getData());
            log.info("getCode:{}", res.getCode());
            log.info("getMsg:{}", res.getMsg());
        }*/
        // 判断是否从编辑界面进来的，前面有"session.setAttribute("getId",getId);",在这里获取，并remove掉；
        /**
         *  如果 前台 noticeId为空则是添加通知，否则是修改数据
         */
        if (!StringUtils.isEmpty(session.getAttribute("noticeId"))) {
            menuId = (Long) session.getAttribute("noticeId");
            NoticesList inform = informDao.findOne(menuId);
            menu.setNoticeTime(inform.getNoticeTime());
            menu.setNoticeId(menuId);
            session.removeAttribute("noticeId");
            informService.save(menu);
        } else {
            menu.setNoticeTime(new Date());
            menu.setUserId(userId);
            NoticesList noticeList = informService.save(menu);
            List<User> userList = uDao.findByFatherId(userId);
            for (User user : userList) {
                informrelationservice.save(new NoticeUserRelation(noticeList, user, false));
            }
        }
        // 执行业务代码
        System.out.println("此操作是正确的");
        req.setAttribute("success", "后台验证成功");
        System.out.println("是否进入最后的实体类信息：" + menu);
        return "forward:/informedit";
    }

    /**
     * 查看通知详情
     */
    @RequestMapping("informshow")
    public String informShow(HttpServletRequest req, Model model, @RequestParam("id") Long noticeId) {
        if (!StringUtils.isEmpty(req.getParameter("read"))) {
            if (("0").equals(req.getParameter("read"))) {
                Long relationId = Long.parseLong(req.getParameter("relationid"));
                NoticeUserRelation relation = informrelationDao.findOne(relationId);
                relation.setRead(true);
                informrelationservice.save(relation);
            }
        }
        NoticesList notice = informDao.findOne(noticeId);
        User user = uDao.findOne(notice.getUserId());
        model.addAttribute("notice", notice);
        model.addAttribute("userName", user.getUserName());
        return "inform/informshow";
    }

    /**
     * 通知管理删除
     */
    @RequestMapping("infromdelete")
    public String infromDelete(HttpSession session, HttpServletRequest req) {
        Long noticeId = Long.parseLong(req.getParameter("id"));
        Long userId = Long.parseLong(session.getAttribute("userId") + "");
        NoticesList notice = informDao.findOne(noticeId);
        if (!Objects.equals(userId, notice.getUserId())) {
            System.out.println("权限不匹配，不能删除");
            session.setAttribute("errormess", "权限不匹配，不能删除");
            return "redirect:/notlimit";
        }
        System.out.println(noticeId);
        informService.deleteOne(noticeId);
        return "redirect:/infrommanage";
    }

    /**
     * 通知列表删除
     */
    @RequestMapping("informlistdelete")
    public String informListDelete(HttpServletRequest req, HttpSession session) {
        Long userId = Long.parseLong(session.getAttribute("userId") + "");
        Long noticeId = Long.parseLong(req.getParameter("id"));
        NoticeUserRelation relation = informrelationDao.findByUserIdAndNoticeId(uDao.findOne(userId),
                informDao.findOne(noticeId));
        if (Objects.isNull(relation)) {
            System.out.println("权限不匹配，不能删除");
            return "redirect:/notlimit";
        }
        informrelationservice.deleteOne(relation);
        return "forward:/infromlist";
    }

    //通知转发
    @RequestMapping("forwardother")
    public String forwardOther(@SessionAttribute("userId") Long userId, @RequestParam(value = "noticeId") Long noticeId) {
        List<User> users = uDao.findByFatherId(userId);
        NoticesList nl = informDao.findOne(noticeId);
        List<NoticeUserRelation> nurs = new ArrayList<>();
        for (User user : users) {
            nurs.add(new NoticeUserRelation(nl, user, false));
        }
        informrelationservice.saves(nurs);
        return "redirect:/infromlist";
    }
}
